<?php
/**
 * Created by 惠达浪
 * Email: crazys@126.com
 * Date: 2018/11/21
 * Time: 23:56
 */

namespace app\lib\exception;

use app\lib\enum\ErrorCodeEnum;
use Exception;
use think\Exception\Handle;
use think\facade\Config;
use think\facade\Log;
use think\facade\Response;

/**
 * 自定义异常处理
 * @package app\lib\exception
 */
class ExceptionHandle extends Handle {
    private $code; //http状态码
    private $msg; //错误信息
    private $errorCode; //错误代码

    /**
     * 重载系统异常处理
     * @param Exception $e 系统异常
     * @return \think\Response|\think\response\Json
     */
    public function render(Exception $e) {
        if ($e instanceof BaseException) {
            //如果是自定义异常，则控制http状态码，不需要记录日志
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        } else {
            if (Config::get('app_debug')) {
                // 调试状态下显示TP默认的异常页面
                return parent::render($e);
            }

            $this->code = 500;
            $this->msg = '抱歉，服务器发生错误。';
            $this->errorCode = ErrorCodeEnum::UNKNOWN_ERROR;

            //非自定义异常，记录日志
            Log::record($e->getMessage(), 'error');
        }

        $result = [
            'errorCode' => $this->errorCode,
            'msg' => $this->msg
        ];

        return Response::create($result, 'json', $this->code);
    }
}